#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 15 21:56:32 2019
@author: youxinlin
"""
# VOC数据集转txt yolo格式指定类别
import copy
from lxml.etree import Element, SubElement, tostring, ElementTree

import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
import shutil

# classes = ["car", "truck", "bus", "person"]  # 类别c
classes = ["abandon object"]  # 类别c

path = "/home/lixu/develop/COCO/"

def convert(size, box):
    dw = 1. / size[0]
    dh = 1. / size[1]
    x = (box[0] + box[1]) / 2.0
    y = (box[2] + box[3]) / 2.0
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh
    return (x, y, w, h)


def convert_annotation(image_id):
    image_id = image_id[0: -4]
    in_file = open('/home/lixu/develop/COCO/Annotations/%s.xml' % (image_id))

    out_file = open('/home/lixu/develop/COCO/labels/%s.txt' % (image_id), 'w')  # 生成txt格式文件

    tree = ET.parse(in_file)
    root = tree.getroot()
    size = root.find('size')
    w = int(size.find('width').text)
    h = int(size.find('height').text)

    for obj in root.iter('object'):
        cls = obj.find('name').text
        if cls not in classes:
            continue
        cls_id = classes.index(cls)
        xmlbox = obj.find('bndbox')
        b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
             float(xmlbox.find('ymax').text))
        bb = convert((w, h), b)
        out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
        local_img_name = '/home/lixu/develop/COCO/JPEGImages/'
        # 指定要复制的图片路径
        path = '/home/lixu/develop/COCO/images/'
        # 指定存放图片的目录
        new_obj_name = image_id + '.jpg'
        shutil.copy(local_img_name  + image_id +".jpg" , path +  new_obj_name)





list_file_train = os.listdir("/home/lixu/develop/COCO/Annotations/")


for image_id in list_file_train:
    convert_annotation(image_id)
